package mapper.datasource;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class MapperApiDataSourceAutoConfigure {

    @Autowired
    private DatasourceConfigure datasourceConfigure;

    //Map<Object, Object> mapperApiDatasourceMap = new HashMap<>();

    private DataSource create(Map<String, String> config) {
        return new PooledDataSource(
                config.get("driver-class-name"),
                config.get("url"),
                config.get("username"),
                config.get("password")
        );
    }

    private Map<String, String> getDatasourceMap(Map<String, Object> config) {
        return new HashMap<>() {{
            put("driver-class-name", config.get("driver-class-name").toString());
            put("url", config.get("url").toString());
            put("username", config.get("username").toString());
            put("password", config.get("password").toString());
        }};
    }

    /**
     * 动态数据源
     * @return
     */
    @Primary
    @Bean(name = "mapperApiDataSource")
    public DataSource mapperApiDataSource() {
        MapperApiDatasource mapperApiDatasource = new MapperApiDatasource();

        // 多数据源map
        Map<String, Object> config = datasourceConfigure.getDatasource();
        DataSourceContextHolder.put("default", create(getDatasourceMap(config)));
        config.keySet().forEach(key-> {
            if("".equals(key) || "druid".equals(key) || "url".equals(key) ||
                    "username".equals(key) || "password".equals(key) ||
                    "driver-class-name".equals(key) || DataSourceContextHolder.containsKey(key)) {
                return;
            }

            DataSourceContextHolder.put(key, create(getDatasourceMap((Map<String, Object>) config.get(key))));
        });

        // 默认数据源
        mapperApiDatasource.setDefaultTargetDataSource(DataSourceContextHolder.get(DataSourceContextHolder.DEFAULT_DATASOURCE));
        // 配置多数据源
        mapperApiDatasource.setTargetDataSources(DataSourceContextHolder.getTargetDataSources());

        return mapperApiDatasource;
    }

    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(mapperApiDataSource());
    }

}
